<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
      >
        <template slot-scope="scope" slot="menuLeft">
          <el-button
            type="primary"
            size="small"
            v-permission="permissionList.submitBtn"
            @click.stop="handleBatchSubmit()"
            >提 交
          </el-button>
          <el-button type="primary" size="small" @click.stop="handleExport()"
            >导 出
          </el-button>
          <el-button
            type="primary"
            size="small"
            :hidden="true"
            v-if="false"
            @click.stop="handlePrint()"
            >打 印
          </el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click.stop="handleView(scope.row, scope.index)"
            >预 览
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-tickets"
            v-if="
              scope.row.isDecompose == null &&
              (scope.row.checkStatus == '0' || scope.row.checkStatus == '3')
            "
            v-permission="permissionList.decomposeBtn"
            @click.stop="handleDecompose(scope.row, scope.index)"
            >分 解
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-tickets"
            v-if="
              scope.row.isDecompose == '1' &&
              (scope.row.checkStatus == '0' || scope.row.checkStatus == '3')
            "
            v-permission="permissionList.updateDecomposeBtn"
            @click.stop="editDecompose(scope.row, scope.index)"
            >编辑分解信息
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            v-if="scope.row.checkStatus == '0' || scope.row.checkStatus == '3'"
            v-permission="permissionList.editBtn"
            @click.stop="handleEdit(scope.row, scope.index)"
            >编 辑
          </el-button>
	  <el-button
            type="text"
            size="small"
            icon="el-icon-delete"           
            v-permission="permissionList.delBtn"
            @click.stop="handleDelete(scope.row, scope.index)"
            >删 除
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-check"
            v-if="scope.row.checkStatus == '1'"
            v-permission="permissionList.auditBtn"
            @click.stop="handleAudit(scope.row, scope.index)"
            >审 批
          </el-button>
        </template>
      </avue-crud>
      <open-dialog :title="title" :DialogVisible.sync="dialogVisible">
        <div class="title">周合计信息</div>
        <avue-crud :data="[form]" :option="weekSummaryOption"></avue-crud>
        <div style="height: 10px"></div>
        <dynamic-crud
          :title="planDetaiTitle"
          :data="dayPlanData"
          :option="dayPlanOption"
          v-if="boxType != 'edit'"
          :rowAdd="dayPlanRowAdd"
          :button="boxType == 'decompose'"
          :tableLoading="dayPlanLoading"
        >
        </dynamic-crud>
        <div v-if="showAuditSuggest">
          <div class="title">审批建议</div>
          <avue-form
            style="margin-top: 10px"
            :option="auditOption"
            v-model="form"
          >
          </avue-form>
        </div>
        <template slot="footer" v-if="boxType != 'view'">
          <template v-if="boxType == 'audit'">
            <el-button type="primary" @click="handleAuditSubmit(true)"
              >审批通过</el-button
            >
            <el-button type="primary" @click="handleAuditSubmit(false)"
              >审批不通过</el-button
            >
          </template>
          <el-button v-else type="primary" @click="handleConfirm"
            >确 认</el-button
          >
          <el-button @click="handleCancle">取 消</el-button>
        </template>
      </open-dialog>
      <open-dialog :title="title" :DialogVisible.sync="dialogVisibleView">
        <div class="title">周合计信息</div>
        <avue-crud :data="[form]" :option="weekSummaryOptionView">
          <template slot="receiptFilePath" slot-scope="{ row }">
            <el-link type="primary" :href="row.receiptFilePath">下载</el-link>
          </template>
        </avue-crud>
        <div style="height: 10px"></div>
        <dynamic-crud
          :title="planDetaiTitle"
          :data="dayPlanData"
          :option="dayPlanOption"
          v-if="boxType != 'edit'"
          :rowAdd="dayPlanRowAdd"
          :button="boxType == 'decompose'"
          :tableLoading="dayPlanLoading"
        >
        </dynamic-crud>
        <div v-if="showAuditSuggest">
          <div class="title">审批建议</div>
          <avue-form
            style="margin-top: 10px"
            :option="auditOption"
            v-model="form"
          >
          </avue-form>
        </div>
        <template slot="footer" v-if="boxType != 'view'">
          <template v-if="boxType == 'audit'">
            <el-button type="primary" @click="handleAuditSubmit(true)"
              >审批通过</el-button
            >
            <el-button type="primary" @click="handleAuditSubmit(false)"
              >审批不通过</el-button
            >
          </template>
          <el-button v-else type="primary" @click="handleConfirm"
            >确 认</el-button
          >
          <el-button @click="dialogVisibleView=false">取 消</el-button>
        </template>
      </open-dialog>

      <open-dialog :title="title" :DialogVisible.sync="dialogVisibleUpdate">
        <div class="title">月度合计信息</div>
        <avue-crud :data="[form]" :option="weekSummaryOptionView">
          <template slot="receiptFilePath" slot-scope="{ row }">
            <el-link type="primary" :href="row.receiptFilePath">下载</el-link>
          </template>
        </avue-crud>
        <div style="height: 10px"></div>
        <dynamic-crud
          :title="planDetaiTitle"
          :data="dayPlanData"
          :option="dayPlanOption"
          :rowAdd="dayPlanRowAdd"
          :button="boxType == 'updateDecompose'"
          :tableLoading="dayPlanLoading"
        >
        </dynamic-crud>
        <template slot="footer">
          <el-button type="primary" @click="updateHandleConfirm"
            >确 认</el-button
          >
          <el-button @click="handleCancleUpdate">取 消</el-button>
        </template>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import baseCrud from "@/mixins/base-crud";
import {
  submitObj,
  auditObj,
  delObj,
  decompose,
  updateDecompose,
} from "@/api/subway/swstplanweek";
import {
  fetchListes as fetchDayPlanList,
  addList,
} from "@/api/subway/swstplanday";
import { nowYear,nowMonth,tableOptionEdit,tableOptionView } from "@/const/crud/subway/swstplanweek";

export default {
  name: "plan-week",
  mixins: [baseCrud("subway/swstplanweek")],
  data() {
    return {
      params: {
        planType: this.planType,
      },
      dialogVisible: false,
      dialogVisibleView: false,
      dialogVisibleUpdate: false,
      dayPlanData: [],
      auditOption: {
        menuBtn: false,
        column: [
          {
            label: "审批建议",
            prop: "checkSuggest",
            type: "textarea",
            placeholder: " ",
            disabled: true,
            span: 24,
          },
        ],
      },
      dayPlanLoading: false,
      title: "",
      boxType: "",
      searchForm: {
        workTime: nowYear,
        planMonth: nowMonth,
        checkStatus: '0'
      }
    };
  },
  props: {
    planDetaiTitle: String,
    planType: {
      type: Number,
      required: true,
    },
    exportName: String,
    dayPlanOption: Object,
    permissionList: Object,
  },
  computed: {
    weekSummaryOption() {
      let column = this.deepClone(tableOptionEdit.column);
      column.forEach((c) => {
        c.search = false;
      });
      return Object.assign(
        {},
        tableOptionEdit,
        {
          header: false,
          menu: false,
          selection: false,
          index: false,
        },
        { column }
      );
    },
    weekSummaryOptionView() {
      let column = this.deepClone(tableOptionView.column);
      column.forEach((c) => {
        c.search = false;
      });
      return Object.assign(
        {},
        tableOptionView,
        {
          header: false,
          menu: false,
          selection: false,
          index: false,
        },
        { column }
      );
    },
    showAuditSuggest() {
      return (
        this.boxType == "audit" ||
        (this.boxType == "view" && this.form.checkStatus != 0)
      );
    },
  },
  methods: {
    getDayPlanList() {
      this.dayPlanLoading = true;
      this.dayPlanData = [];
      const params = {
        planWeekId: this.form.id,
      };
      return fetchDayPlanList(this.planType, params).then((response) => {
        let records = response.data.data;
        records.forEach((r) => (r.$cellEdit = false));
        this.dayPlanData = records;
        this.dayPlanLoading = false;
      });
    },
    handleView(row) {
      this.title = "预览";
      this.boxType = "view";
      this.form = this.deepClone(row);
      this.form.receiptFilePath = "/admin/sys-file/" + row.receiptFilePath;
      this.auditOption.column[0].disabled = true;
      if(this.planType == 1){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[10].disabled = true;
        this.dayPlanOption.column[12].disabled = true;
      }else if(this.planType == 2){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[10].disabled = true;
      }else if(this.planType == 3 ||this.planType == 4){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[12].disabled = true;
        this.dayPlanOption.column[14].disabled = true;
      }
      this.getDayPlanList();
      this.dialogVisibleView = true;
    },
    handleEdit(row) {
      this.title = "编辑";
      this.boxType = "edit";
      if (row.planNumberNow == null) {
        // 如果为null会默认成0
        row.planNumberNow = undefined;
      }
      this.form = this.deepClone(row);
      this.form.$cellEdit = true;
      this.dialogVisible = true;
    },
    handleDecompose(row) {
      if(this.planType == 1){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[10].disabled = false;
        this.dayPlanOption.column[12].disabled = false;
      }else if(this.planType == 2){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[10].disabled = false;
      }else if(this.planType == 3 ||this.planType == 4){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[12].disabled = false;
        this.dayPlanOption.column[14].disabled = false;
      }
      this.dialogVisibleView = true;
      this.title = "分解";
      this.boxType = "decompose";
      this.form = this.deepClone(row);
      this.form.receiptFilePath = "/admin/sys-file/" + row.receiptFilePath;
      let weekPlan = this.findObject(this.dayPlanOption.column, "planWeek");
      let weeks = this.form.planWeek.split(",");
      weekPlan.dicData = weeks.map((m) => {
        return {
          label: m + "周",
          value: m,
        };
      });
      weekPlan.value = weeks[0];
      if (weeks.length === 1) {
        // 单周期的不能选择月份
        weekPlan.cell = false;
      } else {
        weekPlan.cell = true;
      }
      this.getDayPlanList().then(() => {
      this.dayPlanData.ticketType=this.form.ticketType;
        this.dayPlanData.forEach((wp) => {
          if (wp.checkStatus != 2) {
            // 不是审批通过状态的数据才能操作
            wp.$cellEdit = true;
          }
        });
      });
    },
     //高级删除操作
     handleDelete(row) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delObj(row)
            .then((data) => {
              this.$message.success("删除成功");
              this.getList(this.page);
              done();
            })
            .catch(() => {
              loading();
            });
        });
      },
    editDecompose(row) {
      this.title = "编辑分解信息";
      this.boxType = "updateDecompose";
      this.form = this.deepClone(row);
      this.form.receiptFilePath = "/admin/sys-file/" + row.receiptFilePath;
      let weekPlan = this.findObject(this.dayPlanOption.column, "planWeek");
      let weeks = this.form.planWeek.split(",");
      weekPlan.dicData = weeks.map((m) => {
        return {
          label: m + "周",
          value: m,
        };
      });
      weekPlan.value = weeks[0];
      if (weeks.length === 1) {
        // 单周期的不能选择月份
        weekPlan.cell = false;
      } else {
        weekPlan.cell = true;
      }
      this.getDayPlanList().then(() => {
        this.dayPlanData.forEach((wp) => {
          if (wp.checkStatus != 2) {
            // 不是审批通过状态的数据才能操作
            wp.$cellEdit = true;
          }
        });
      });
      if(this.planType == 1){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[10].disabled = false;
        this.dayPlanOption.column[12].disabled = false;
      }else if(this.planType == 2){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[10].disabled = false;
      }else if(this.planType == 3 ||this.planType == 4){
        this.dayPlanOption.column[4].disabled = false;
        this.dayPlanOption.column[12].disabled = false;
        this.dayPlanOption.column[14].disabled = false;
      }
      this.dialogVisibleUpdate = true;
    },
    handleAudit(row) {
      this.boxType = "audit";
      this.title = "审批";
      this.form = this.deepClone(row);
      this.form.receiptFilePath = "/admin/sys-file/" + row.receiptFilePath;
      this.auditOption.column[0].disabled = false;
      if(this.planType == 1){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[10].disabled = true;
        this.dayPlanOption.column[12].disabled = true;
      }else if(this.planType == 2){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[10].disabled = true;
      }else if(this.planType == 3 ||this.planType == 4){
        this.dayPlanOption.column[4].disabled = true;
        this.dayPlanOption.column[12].disabled = true;
        this.dayPlanOption.column[14].disabled = true;
      }
      this.getDayPlanList();
      this.dialogVisibleView = true;
    },
    handleAuditSubmit(pass) {
      this.form.checkStatus = pass ? "2" : "3";
      auditObj(this.form).then((response) => {
        this.$message.success("审批成功");
        this.dialogVisibleView = false;
        this.getList(this.page);
      });
    },
    handleConfirm() {
      if (this.boxType == "edit") {
        this.rowUpdate(
          this.form,
          0,
          () => {
            this.dialogVisible = false;
          },
          () => {}
        );
      } else if (this.boxType == "decompose") {
        let planNum =
          this.form.planNumberNow != null
            ? this.form.planNumberNow
            : this.form.planNumberOld;
        let decomposeNum = 0;
        this.dayPlanData.forEach((plan) => {
          decomposeNum += plan.ticketNumber;
        });
        if (this.form.planNumberNow == null) {
          this.$message.info("请先编辑填写现计划数量！");
          return;
        }
        if (decomposeNum > planNum) {
          this.$message.info("分解张数不能大于计划张数");
          return;
        }
        for (const item of this.dayPlanData) {
          if (
            item.planFinishTime == null ||
            item.ticketName == null
          ) {
            this.$message.info(
              "请选择计划完成时间、车票名称！"
            );
            return;
          }
          if (item.ticketPrice == null && item.ticketTimes == null) {
            this.$message.info("请填写票价或车票次数！");
            return;
          }
          if(this.form.ticketType == "YXCP" || this.form.ticketType == "GWP" || this.form.ticketType == "YZDCP"){
            if (item.activeTime == null || item.activeTime == "" || item.latestStartTime == null || item.latestStartTime == "") {
              this.$message.info("车票有效期和最晚启用时间不能为空！");
              return;
            }
            this.$message.info("请填写票价或车票次数！");
            return;
          }
          if (item.ticketNumber == null) {
            this.$message.info("张数不能为空！");
            return;
          }
          if (this.planType == 1) {
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择清洗人1、清洗人2！");
              return;
            }
          }
          if (this.planType == 2) {
            if (item.personName == null) {
              this.$message.info("请选择车票编码员！");
              return;
            }
          }
          if (this.planType == 3) {
            if (item.lineCode == null || item.stationCode == null) {
              this.$message.info("请选择线路、车站！");
              return;
            }
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择配送人1、配送人2！");
              return;
            }
          }
          if (this.planType == 4) {
            if (item.lineCode == null || item.stationCode == null) {
              this.$message.info("请选择线路、车站！");
              return;
            }
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择车票回收员1、车票回收员2！");
              return;
            }
          }
        }
        if (decomposeNum !== planNum) {
          this.$message.info("分解数量和现计划数量不一致，请检查数据！");
          return;
        }
        decompose(this.form.id, this.dayPlanData).then((response) => {
          this.$message.success("分解成功");
          this.getList(this.page);
          this.dialogVisibleView = false;
        });
      }
    },
    updateHandleConfirm() {
      if (this.boxType == "updateDecompose") {
        let planNum =
          this.form.planNumberNow != null
            ? this.form.planNumberNow
            : this.form.planNumberOld;
        let decomposeNum = 0;
        this.dayPlanData.forEach((plan) => {
          decomposeNum += plan.ticketNumber;
        });

        if (this.form.planNumberNow == null) {
          this.$message.info("请先编辑填写现计划数量！");
          return;
        }
        if (decomposeNum > planNum) {
          this.$message.info("分解张数不能大于计划张数");
          return;
        }
        for (const item of this.dayPlanData) {
          if (
            item.planFinishTime == null ||
            item.ticketName == null
          ) {
            this.$message.info(
              "请选择计划完成时间、车票名称！"
            );
            return;
          }
          if (item.ticketPrice == null && item.ticketTimes == null) {
            this.$message.info("请填写票价或车票次数！");
            return;
          }
          if(this.form.ticketType == "YXCP" || this.form.ticketType == "GWP" || this.form.ticketType == "YZDCP"){
            if (item.activeTime == null || item.activeTime == "" || item.latestStartTime == null || item.latestStartTime == "") {
              this.$message.info("车票有效期和最晚启用时间不能为空！");
              return;
            }
            this.$message.info("请填写票价或车票次数！");
            return;
          }
          if (item.ticketNumber == null) {
            this.$message.info("张数不能为空！");
            return;
          }
          if (this.planType == 1) {
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择清洗人1、清洗人2！");
              return;
            }
          }
          if (this.planType == 2) {
            if (item.personName == null) {
              this.$message.info("请选择车票编码员！");
              return;
            }
          }
          if (this.planType == 3) {
            if (item.lineCode == null || item.stationCode == null) {
              this.$message.info("请选择线路、车站！");
              return;
            }
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择配送人1、配送人2！");
              return;
            }
          }
          if (this.planType == 4) {
            if (item.lineCode == null || item.stationCode == null) {
              this.$message.info("请选择线路、车站！");
              return;
            }
            if (item.personName == null || item.personTwoName == null) {
              this.$message.info("请选择车票回收员1、车票回收员2！");
              return;
            }
          }
        }
        if (decomposeNum !== planNum) {
          this.$message.info("分解数量和现计划数量不一致，请检查数据！");
          return;
        }
        updateDecompose(this.form.id, this.dayPlanData).then((response) => {
          this.$message.success("编辑分解信息成功");
          this.getList(this.page);
          this.dialogVisibleUpdate = false;
        });
      }
    },
    handleCancle() {
      this.dialogVisible = false;
    },
    handleCancleUpdate() {
      this.dialogVisibleUpdate = false;
    },
    dayPlanRowAdd(callback) {
      let planWeek = this.findObject(this.dayPlanOption.column, "planWeek");
      callback({ 
        planWeek: planWeek.value,
        ticketType: this.form.ticketType
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.title {
  margin: 10px auto 0;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  background-color: #eee;
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
